package yd.launcher;

import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.dnd.*;
import java.util.ArrayList;
import java.util.List;

public class DraggableListEditor extends JPanel {
    private DefaultListModel<String> listModel;
    private JList<String> list;
    private List<String> dataList;

    public DraggableListEditor(List<String> initialData) {
        this.dataList = new ArrayList<>(initialData);
        initUI();
    }

    private void initUI(){
        // 创建列表模型并填充初始数据
        listModel = new DefaultListModel<>();
        for (String item : dataList) {
            listModel.addElement(item);
        }

        // 创建支持拖放的JList
        list = new JList<>(listModel);
        list.setCellRenderer(new EditableListCellRenderer());
        list.setDropMode(DropMode.INSERT);
        list.setDragEnabled(true);
        list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

        // 设置拖放处理器
        list.setTransferHandler(new ListItemTransferHandler());

        // 添加拖放支持
        new DropTarget(list, DnDConstants.ACTION_MOVE, new ListDropTargetListener(), true);

        // 使用滚动面板
        JScrollPane scrollPane = new JScrollPane(list);

        // 添加按钮面板
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
        JButton addButton = new JButton("添加项");
        addButton.addActionListener(e -> {
            listModel.addElement("");
            dataList.add("");
            list.ensureIndexIsVisible(listModel.size() - 1);
        });

        JButton removeButton = new JButton("删除选中");
        removeButton.addActionListener(e -> {
            int selectedIndex = list.getSelectedIndex();
            if (selectedIndex != -1) {
                listModel.remove(selectedIndex);
                dataList.remove(selectedIndex);
            }
        });

        buttonPanel.add(addButton);
        buttonPanel.add(removeButton);

        // 设置主布局
        setLayout(new BorderLayout());
        add(scrollPane, BorderLayout.CENTER);
        add(buttonPanel, BorderLayout.SOUTH);
    }
    // 自定义单元格渲染器，将每个项渲染为输入框+拖动按钮
    private class EditableListCellRenderer implements ListCellRenderer<String> {
        private final JPanel panel;
        private final JTextField textField;
        private final JLabel dragHandle;

        public EditableListCellRenderer() {
            panel = new JPanel(new BorderLayout());
            panel.setBorder(new EmptyBorder(2, 2, 2, 2));

            textField = new JTextField();
            textField.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));

            dragHandle = new JLabel("≡");
            dragHandle.setBorder(BorderFactory.createEmptyBorder(0, 5, 0, 5));
            dragHandle.setOpaque(true);
            dragHandle.setBackground(new Color(220, 220, 220));
            dragHandle.setCursor(Cursor.getPredefinedCursor(Cursor.MOVE_CURSOR));

            panel.add(textField, BorderLayout.CENTER);
            panel.add(dragHandle, BorderLayout.EAST);
        }
        @Override
        public Component getListCellRendererComponent(JList<? extends String> list, String value,
                                                      int index, boolean isSelected, boolean cellHasFocus) {
            textField.setText(value);

            // 更新背景颜色以反映选择状态
            if (isSelected) {
                panel.setBackground(list.getSelectionBackground());
                textField.setBackground(list.getSelectionBackground());
                dragHandle.setBackground(list.getSelectionBackground().darker());
            } else {
                panel.setBackground(list.getBackground());
                textField.setBackground(list.getBackground());
                dragHandle.setBackground(new Color(220, 220, 220));
            }

            // 添加文档监听器以更新模型
            textField.getDocument().addDocumentListener(new javax.swing.event.DocumentListener() {
                public void changedUpdate(javax.swing.event.DocumentEvent e) {
                    update();
                }
                public void insertUpdate(javax.swing.event.DocumentEvent e) {
                    update();
                }
                public void removeUpdate(javax.swing.event.DocumentEvent e) {
                    update();
                }

                private void update() {
                    int modelIndex = list.getModel().getSize() - index - 1;
                    String newValue = textField.getText();
                    listModel.set(index, newValue);
                    dataList.set(index, newValue);
                }
            });

            return panel;
        }
    }

    // 自定义TransferHandler处理拖放操作
    private class ListItemTransferHandler extends TransferHandler {
        @Override
        public int getSourceActions(JComponent c) {
            return MOVE;
        }

        @Override
        protected Transferable createTransferable(JComponent c) {
            JList<?> list = (JList<?>) c;
            int index = list.getSelectedIndex();
            if (index == -1) return null;

            return new StringTransferable(listModel.getElementAt(index), index);
        }

        @Override
        protected void exportDone(JComponent source, Transferable data, int action) {
            if (action == MOVE) {
                StringTransferable transferable = (StringTransferable) data;
                if (transferable.getIndex() != -1) {
                    listModel.remove(transferable.getIndex());
                    dataList.remove(transferable.getIndex());
                }
            }
        }

        @Override
        public boolean canImport(TransferSupport support) {
            return support.isDataFlavorSupported(StringTransferable.DATA_FLAVOR);
        }

        @Override
        public boolean importData(TransferSupport support) {
            if (!canImport(support)) {
                return false;
            }

            try {
                StringTransferable transferable = (StringTransferable) support.getTransferable()
                        .getTransferData(StringTransferable.DATA_FLAVOR);
                JList.DropLocation dl = (JList.DropLocation) support.getDropLocation();
                int dropIndex = dl.getIndex();

                // 防止拖放到自身位置
                if (transferable.getIndex() != -1 && transferable.getIndex() == dropIndex) {
                    return false;
                }

                // 插入到新位置
                listModel.add(dropIndex, transferable.getValue());
                dataList.add(dropIndex, transferable.getValue());

                return true;
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
        }
    }

    // 自定义Transferable实现
    private static class StringTransferable implements Transferable {
        public static final DataFlavor DATA_FLAVOR = new DataFlavor(StringTransferable.class, "StringTransferable");

        private final String value;
        private final int index;

        public StringTransferable(String value, int index) {
            this.value = value;
            this.index = index;
        }

        public String getValue() {
            return value;
        }

        public int getIndex() {
            return index;
        }

        @Override
        public DataFlavor[] getTransferDataFlavors() {
            return new DataFlavor[]{DATA_FLAVOR};
        }

        @Override
        public boolean isDataFlavorSupported(DataFlavor flavor) {
            return flavor.equals(DATA_FLAVOR);
        }

        @Override
        public Object getTransferData(DataFlavor flavor) {
            if (!isDataFlavorSupported(flavor)) {
                return null;
            }
            return this;
        }
    }
    // 自定义DropTargetListener
    private class ListDropTargetListener implements DropTargetListener {
        @Override
        public void dragEnter(DropTargetDragEvent dtde) {
            // 不需要实现
        }

        @Override
        public void dragOver(DropTargetDragEvent dtde) {
            // 不需要实现
        }

        @Override
        public void dropActionChanged(DropTargetDragEvent dtde) {
            // 不需要实现
        }

        @Override
        public void dragExit(DropTargetEvent dte) {
            // 不需要实现
        }

        @Override
        public void drop(DropTargetDropEvent dtde) {
            // 不需要实现，TransferHandler已经处理
        }
    }
    // 获取更新后的数据列表
    public List<String> getDataList() {
        return new ArrayList<>(dataList);
    }
}